package com.smzd.ccms.actions;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.smzd.ccms.business.ImageService;
import com.smzd.ccms.domain.Image;
import com.smzd.ccms.domain.Site;
import com.smzd.framework.utils.JsonHelper;
import com.smzd.utils.SessionHolder;

@Controller
public class FileUploadController {
	private static final String NO_CALLBACK = "_no_cb_";
	public static File UPLOAD_ROOT;

	@Autowired
	private ImageService imageService;

	@RequestMapping(value = "/uploadfile", method = RequestMethod.GET)
	public String toUploadFilePage() {
		return "uploadfile.ftl";
	}

	@RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
	public String fileUpload(Map<String, Object> model,
			@RequestParam(value = "callback", required = false, defaultValue = NO_CALLBACK) String callback,
			@RequestParam(value = "meta", required = false) String meta, HttpServletRequest request,
			@RequestParam(value = "file") MultipartFile multipartFile) {
		Map<String, Object> root = new HashMap<String, Object>();
		if (callback != null && callback.length() > 0 && !callback.equals(NO_CALLBACK)) {
			root.put("callback", callback);
			model.put("callback", callback);
		}
		root.put("meta", meta);
		String page = "uploadcomplete.ftl";// 你需要一个页面来执行一段js
		if (multipartFile == null) {
			root.put("err", "没有上传文件！");
			model.put("json", JsonHelper.getFailJsonString(root));
			return getMyView(page);
		}
		String origin = multipartFile.getOriginalFilename();
		root.put("origin", origin);
		long size = multipartFile.getSize();
		root.put("size", size);
		System.out.println("----------文件上传，文件大小是" + size);
		if (multipartFile.getSize() > 51200000) {
			root.put("err", "图片大于500M！");
			model.put("json", JsonHelper.getFailJsonString(root));
			return getMyView(page);
		}
		int idx = origin.lastIndexOf(".");
		if (idx < 0) {
			root.put("err", "文件格式不正确！");
			model.put("json", JsonHelper.getFailJsonString(root));
			return getMyView(page);
		}
		String ext = origin.substring(idx);
		if (ext.trim().length() == 0) {
			root.put("err", "文件格式不正确！");
			model.put("json", JsonHelper.getFailJsonString(root));
			return getMyView(page);
		}
		if (!checkFileExt(ext)) {
			root.put("err", "文件格式不正确！");
			model.put("json", JsonHelper.getFailJsonString(root));
			return getMyView(page);
		}
		root.put("ext", ext);

		String name = UUID.randomUUID().toString() + ext;
		root.put("name", name);
		System.out.println("----------文件上传，生成的随机文件名是" + name);
		root.put("path", "/files");

		if (UPLOAD_ROOT == null) {
			ServletContext context = request.getSession().getServletContext();
			File uploadPath = new File(context.getRealPath("/files"));
			uploadPath.mkdirs();
			UPLOAD_ROOT = uploadPath;
		}
		Site site = SessionHolder.getObject(Site.SESSION_KEY_CURRENT_SITE);
		File dir = new File(UPLOAD_ROOT, site.getPath());
		dir.mkdirs();
		try {
			multipartFile.transferTo(new File(dir, name));
		} catch (Exception e) {
			e.printStackTrace();
			model.put("json", JsonHelper.getFailJsonString("文件上传失败！"));
			return getMyView(page);
		}
		root.put("msg", "文件上传成功！");
		Image image = new Image();
		image.setOwner(site.getOwner());
		image.setName(name);
		image.setPath(name);
		image.setType(0);
		imageService.insert(image);
		root.put("id", image.getId());
		model.put("json", JsonHelper.getSuccessJsonString(root));
		return getMyView(page);
	}

	/**
	 * 文件类型检查通过的时候返回true，否则返回false表示文件类型检查不通过。
	 * 
	 * @param ext
	 *            扩展名，带点号（.jpg）
	 * @return
	 */
	private boolean checkFileExt(String ext) {
		return true;
	}

	private String getMyView(String page) {
		return "fileupload/" + page;
	}

}
